<template>
    <div>
        <Form :label-width="150" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form">
                <i-col span="8">
                  <FormItem label="二级集团：" prop="companyName">
                    <two-level-org org-code v-model="formInline.companyName" ></two-level-org>
                  </FormItem>
                </i-col>
                <i-col span="8">
                  <FormItem label="企业名称：">
                    <company-select v-model="formInline.proName"></company-select>
                  </FormItem>
                </i-col>
                <i-col span="8"  v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button class="ivu-btn-reset" @click="cancel">重置</Button>
                    <Button class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </i-col>
              <i-col span="8" v-else>
                <FormItem label="岗位清单名称：" prop="name">
                  <Input v-model="formInline.name" placeholder="请填写岗位清单名称"/>
                </FormItem>
              </i-col>
            </Row>
            <Row class="query-form" v-if="switchFlag">
                <i-col span="8" >
                  <FormItem label="岗位：" prop="postName">
                    <Input v-model="formInline.postName" placeholder="请填写岗位"/>
                  </FormItem>
                </i-col>
                <i-col span="8" offset="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button class="ivu-btn-reset" @click="cancel">重置</Button>
                    <Button class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" @on-sort-change="querySort"
                :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                        @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal  :title="modalTitle" :transfer=false v-model="model1" :closable="false" :mask-closable="false" :width="900" :styles="{top: '20px'}">
            <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="定制岗位：" prop="postId">
                            <Input class="postNameClass" disabled v-if="isUpdate" type="text" v-model="formData.postName"></Input>
                            <userDom ref="userDom" :selectData='setCurrentScreenPositionName' :singleChoice=false :ifUser="false" @setData = "setScreenPositionId" v-else></userDom>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="岗位清单名称：" prop="name">
                            <Input v-model="formData.name" placeholder="请填写岗位清单名称"/>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div style="height: 400px; overflow-y: auto; overflow-x: auto;">
                <Tree v-if="isHead" :load-data="loadData" @on-select-change="treeSelect" show-checkbox :data="orderTreeHead"></Tree>
                <z-tree v-else :nodes="orderTree"
                    :setting="setingTree"
                    @onCreated="handleCreated"
                />
            </div>
            <div slot="footer">
                <Button type="primary"  class='ivu-btn-save' @click="saveInfo" :loading="buttonLoading">确定</Button>
                <Button type="primary"  class='ivu-btn-cancel' @click="model1=false" :loading="buttonLoading">取消</Button>
            </div>
        </Modal>
        <Modal :transfer=false v-model="model2"  :closable="false" :mask-closable="false" :width="900" :styles="{top: '20px'}">
            <Form :label-width="160">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="岗位清单名称：">
                            {{copyData.name}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="定制岗位：">
                            {{copyData.postName}}
                        </FormItem>
                    </i-col>
                </Row>
              <Row :gutter="16">
                <i-col span="24">
                  <FormItem label="当前岗位用户列表：">
                    {{copyData.userNames}}
                  </FormItem>
                </i-col>
              </Row>
            </Form>
            <div style="height: 400px; overflow-y: auto; overflow-x: auto;">
                <Tree v-if="isHead"  show-checkbox :data="orderTreeHead"></Tree>
                <z-tree v-else :nodes="orderTree"
                    :setting="setingTree"
                />
            </div>
            <div slot="footer">
                <Button class="ivu-btn-cancel"  @click="model2=false" >关闭</Button>
            </div>
        </Modal>
        <Modal :transfer=false v-model="model3" title="岗位变更" :closable="false" :mask-closable="false" :width="900" >
            <Form ref="formPosition" :model="formData" label-position="top">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="岗位：" prop="postId">
                            <cascaderPosition ref="childUser" @setOrgInfo="setScreenPositionId2" @setOrgname="setScreenPositionName"
                                              :setCurrentName="setCurrentScreenPositionName"></cascaderPosition>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary"  class='ivu-btn-save' @click="saveInfo2" :loading="buttonLoading">确定</Button>
                <Button type="primary"  class='ivu-btn-cancel' @click="model3=false" :loading="buttonLoading">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import treeDom from "../../../components/tree-dom.vue"
import {sessionStorage} from '@/common/cacheUtils.js';
import {Api} from '../../../api'
import cascaderPosition from '../../../components/cascader-position'
import zTree from "@/components/ztree.vue"
import cascaderDom from "../../../components/cascader-dom.vue"

import userDom from "@/components/input-user.vue";


export default {
  name: "apsgItemPlan",
  components: {treeDom, cascaderDom, cascaderPosition, zTree, userDom},
  data() {
    return {
      switchFlag: false,
      buttonLoading: false,
      rootOrgId: '',
      isHead: true,
      ztreeObj: null,
      lastPostName: "",
                modalTitle:"",
                setCurrentScreenPositionName: {},
                loginId:"",
                currentUserId:"",
                positions: [],
                isUpdate: false,
                model1: false,
                model2: false,
                model3: false,
                loading: false,
                isRole: false,
                isPost: false,
                isPro: false,
                isProType: false,
                formInline: {postId:"",name:""},
                copyData:{},
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        fixed: 'left',
                        align: 'center',
                    },
                    {
                        title: '岗位清单名称',
                        align: 'center',
                        key: 'name',
                        minWidth: 140,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.name || '--')
                            ]);
                        }
                    },
                    {
                        title: '创建人',
                        align: 'center',
                        key: 'creatorName',
                        minWidth: 90,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.creatorName || '--')
                            ]);
                        }
                    },
                    {
                        title: '所属公司',
                        align: 'center',
                        key: 'companyName',
                        minWidth: 140,
                    },
                    {
                        title: '所属部门',
                        align: 'center',
                        key: 'proName',
                        minWidth: 140,
                    },
                    {
                        title: '所属岗位',
                        align: 'center',
                        key: 'postName',
                        minWidth: 140,
                    },
                    {
                        title: '创建日期',
                        align: 'center',
                        key: 'createTimeStr',
                        sortable: 'custom',
                        minWidth: 160,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.createTimeStr || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 230,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.isHead = true;
                                            this.orderTreeHead= [
                                                {
                                                    id:1,
                                                    loading: true,
                                                    title: '隐患条目',
                                                    expand: false,
                                                    children: []
                                                }
                                            ],
                                            this.orderTree = [{
                                                id:1,
                                                name: '隐患条目',
                                                open: true,
                                                pid:0
                                            }];
                                            this.copyData = Object.assign(params.row);
                                            this.$http.get(Api.queryUsersByPositionId + params.row.postId).then(function(res) {
                                                let userNames = "";
                                                res.data.data.forEach(item=>{
                                                  userNames += (item.userName + " ")
                                                })
                                                this.$set(this.copyData,'userNames',userNames)
                                            })
                                            this.model2 = true;
                                            this.$http.get(Api.apsgItemPlan + '/tree/position', {
                                                params: {parentId: 1, pid: params.row.id,positionId: params.row.postId}
                                            }).then(function(res){
                                                if(res.data.length>0){
                                                    this.isHead = false;
                                                     this.orderTree = [{
                                                        id:1,
                                                        name: '隐患条目',
                                                        open: true,
                                                        pid:0
                                                    }];
                                                    res.data.forEach(item=>{
                                                        this.orderTree= this.orderTree.concat(item);
                                                    })
                                                }else{
                                                    this.orderTreeHead= [
                                                        {
                                                            id:1,
                                                            loading: false,
                                                            title: '隐患条目',
                                                            expand: false,
                                                            children: []
                                                        }
                                                    ];
                                                }
                                            }, function(res){
                                                this.$Message.error('请求失败');
                                            });
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (this.currentUserId != params.row.creator&&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)  ? '#d0d0d0':'',
                                        pointerEvents:  (this.currentUserId != params.row.creator &&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) ? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.updateRow(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (this.currentUserId != params.row.creator&&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)  ? '#d0d0d0':'',
                                        pointerEvents:  (this.currentUserId != params.row.creator &&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) ? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.model3 = true;
                                            this.formData.id = params.row.id;
                                        }
                                    }
                                }, '岗位变更'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                         color: (this.currentUserId != params.row.creator &&this.loginId != this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) ? '#d0d0d0':'red',
                                         pointerEvents:  (this.currentUserId != params.row.creator&&this.loginId !=this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) ? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteRow(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                infos: [],
                tableHeight: 0,
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
                ruleCustom: {
                    name: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    isPublic: [
                        {
                            required: true,
                            type: 'number',
                            message: '  ',
                            trigger: 'change'
                        }
                    ],
                    state: [
                        {
                            type: 'number',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    planType: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    startTime: [
                        {
                            required: true,
                            message: '  ',
                            type: 'date',
                            trigger: 'blur,change'
                        }
                    ],
                    endTime: [
                        {
                            required: true,
                            message: '  ',
                            type: 'date',
                            trigger: 'blur,change'
                        }
                    ],
                },
                formData: {},
                publicList: [
                    {
                        id: 0,
                        label: '不公开'
                    },
                    {
                        id: 1,
                        label: '公开'
                    }
                ],
                stateList: [
                    {
                        id: 0,
                        label: '禁用'
                    },
                    {
                        id: 1,
                        label: '正常'
                    }
                ],
                orderTree: [
                    {
                        id:1,
                        name: '隐患条目',
                        open: true,
                        pid:0
                    }
                ],
                orderTreeHead: [
                    {
                        id:1,
                        loading: false,
                        title: '隐患条目',
                        expand: false,
                        children: []
                    }
                ],
                setingTree: {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "parent_id",
                        },
                        key:{
                            children: "childList"
                        },
                    },
                    view: {
                        showIcon: false,
                        showLine:true,
                        // addHoverDom: this.addHoverDom,
                        // removeHoverDom: this.removeHoverDom,
                    },
                    switchFlag: false
                },
            }
        },
        mounted(){
            this.currentUserId = sessionStorage('userId').getObject('userId').userId;
            this.loginId = sessionStorage('userId').getObject('userId').loginId;
            let user = sessionStorage('userId').getObject('userId');
            this.rootOrgId =  user.companyId;
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.query();
        },
        methods:{
            treeSelect(nodes,node){
                this.orderTreeHead[0].loading = true;
                this.$http.get(Api.apsgItemPlan + '/tree/position', {
                    params: {parentId: 1, pid: this.formData.id,positionId:this.formData.postId}
                }).then(function(res){
                    if(res.data.length>0){
                        this.isHead = false;
                         this.orderTree = [{
                            id:1,
                            name: '隐患条目',
                            open: true,
                            pid:0
                        }];
                        res.data.forEach(item=>{
                            this.orderTree= this.orderTree.concat(item);
                        })
                    }else{
                        this.orderTreeHead= [
                            {
                                id:1,
                                loading: false,
                                title: '隐患条目',
                                expand: false,
                                children: []
                            }
                        ];
                    }
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            handleCreated(ztreeObj) {
                this.ztreeObj = ztreeObj;
            },
            loadData(){

            },
            setOrgInfo(data){
                this.formInline.postId = data[data.length - 1];
            },
            query(){
                this.loading = true;
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                    postId: user.companyId,
                    creator:user.userId,
                    order: this.formInline.order,
                    key: this.formInline.key,
                };
                if(this.formInline.postId != ""&&this.formInline.postId != undefined){
                    data.postId = this.formInline.postId;
                }
                if(this.formInline.postName != ""&&this.formInline.postName != undefined){
                    data.postName = this.formInline.postName;
                }
                if(this.formInline.companyName != ""&&this.formInline.companyName != undefined){
                  data.companyName = this.formInline.companyName;
                }
                if(this.formInline.proName != ""&&this.formInline.proName != undefined){
                  data.proName = this.formInline.proName;
                }


                if(this.formInline.name != "")
                    data.name = this.formInline.name;
                this.$http.get(Api.apsgItemPlan, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            setScreenPositionName(data) {
                this.formData.postName = data;
            },
            setScreenPositionId(data) {
                data.forEach(item=>{
                    this.formData.postId += (item + ",")
                })
                this.isHead = true;
                this.orderTreeHead= [
                    {
                        id:1,
                        loading: true,
                        title: '隐患条目',
                        expand: false,
                        children: []
                    }
                ];
                this.$http.get(Api.apsgItemPlan + '/tree/position', {
                    params: {parentId: 1, pid: this.formData.id,positionId:data[0]}
                }).then(function(res){
                    if(res.data.length>0){
                        this.isHead = false;
                        this.orderTree = [{
                            id:1,
                            name: '隐患条目',
                            open: true,
                            pid:0
                        }];
                        res.data.forEach(item=>{
                            this.orderTree= this.orderTree.concat(item);
                        })
                    }else{
                        this.orderTreeHead= [
                            {
                                id:1,
                                loading: false,
                                title: '隐患条目',
                                expand: false,
                                children: []
                            }
                        ];
                    }
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            setScreenPositionId2(data) {
                data.forEach(item=>{
                    this.formData.postId += (item + ",")
                })
            },
            cancel(){
                this.formInline = {postId:"",name:"",postName:''};
                setTimeout(()=>{
                    this.$refs.existOrg.setCurrentOrg();
                },100)
                this.query();
            },
            addInfo(){
                this.modalTitle="岗位清单新增"
                this.orderTree = [{
                    id:1,
                    name: '隐患条目',
                    open: true,
                    pid:0
                }];
                this.lastPostName = "";
                this.model1 = true;
                this.isUpdate = false;
                this.formData={
                    name:"",
                    postId:"",
                    postName:""
                },
                this.setCurrentScreenPositionName = {};
                // setTimeout(()=>{
                //     this.$refs.childUser.setCurrentUser();
                // },200);
                this.$refs.userDom.setCurrentInfo();
                this.isHead = true;
                this.orderTreeHead= [
                    {
                        id:1,
                        loading: false,
                        title: '隐患条目',
                        expand: false,
                        children: []
                    }
                ]
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            updateRow(row){
                this.isHead = true;
                this.buttonLoading = true;
                this.orderTreeHead= [
                    {
                        id:1,
                        loading: true,
                        title: '隐患条目',
                        expand: false,
                        children: []
                    }
                ];
                this.orderTree = [{
                        id:1,
                        name: '隐患条目',
                        open: true,
                        pid:0
                    }];
                this.modalTitle = "岗位清单修改";
                this.lastPostName = "";
                this.isUpdate = true;
                this.formData = JSON.parse(JSON.stringify(row));
                this.setCurrentScreenPositionName = {value: row.postId, label: row.postName};
                setTimeout(()=>{
                    this.$refs.childUser.setCurrentUser();
                },200);
                this.model1 = true;
                this.$http.get(Api.apsgItemPlan + '/tree/position', {
                    params: {parentId: 1, pid: row.id,positionId:row.postId}
                }).then(function(res){
                    if(res.data.length>0){
                        this.isHead = false;
                         this.orderTree = [{
                            id:1,
                            name: '隐患条目',
                            open: true,
                            pid:0
                        }];
                        res.data.forEach(item=>{
                            this.orderTree= this.orderTree.concat(item);
                        })
                        this.buttonLoading = false;
                    }else{
                        this.orderTreeHead= [
                            {
                                id:1,
                                loading: false,
                                title: '隐患条目',
                                expand: false,
                                children: []
                            }
                        ];
                        this.buttonLoading = false;
                    }
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        let tree = this.ztreeObj.getCheckedNodes(true);
                        let checkNode = [];
                        tree.map((i, j)=>{
                            if(i.root == 'false')
                                checkNode.push({itemId: '',itemTypeId:i.id});
                            else
                                checkNode.push({itemId: i.id,itemTypeId:''});
                        })
                        this.formData.itemPlanDetailList = checkNode;
                        this.formData.apsgItem = this.apsgItemList;
                        if(this.isUpdate){
                            this.$http.put(Api.apsgItemPlan,this.formData).then(function(response){
                                this.model1 = false;
                                this.query();
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
                            }, function(response){
                                this.$Message.error({
                                    content: '更新失败',
                                    duration: 4
                                });
                            });
                        }else{
                            let user = sessionStorage('userId').getObject('userId');
                            this.formData.creator = user.userId;
                            this.formData.creatorName = user.userName;
                            this.$http.post(Api.apsgItemPlan,this.formData).then(function(response){
                                this.model1 = false;
                                this.$Message.success({
                                    content: '保存成功',
                                    duration: 4
                                });
                                this.query();
                            }, function(response){
                                this.$Message.error({
                                    content: '保存失败',
                                    duration: 4
                                });
                            });
                        }
                    }
                });
            },
            saveInfo2(){
                if(this.formData.postId == undefined || this.formData.postId == ''){
                    this.$Message.error({
                        content: '请选择要变变更岗位！',
                        duration: 4
                    });
                }
                this.$http.put(Api.apsgItemPlan + '2',this.formData).then(function(response){
                    this.model3 = false;
                    this.query();
                    this.$Message.success({
                        content: '保存成功',
                        duration: 4
                    });
                }, function(response){
                    this.$Message.error({
                        content: '更新失败',
                        duration: 4
                    });
                });
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.apsgItemPlan, {params:{
                                id: row.id,
                                updateUserId: this.currentUserId,
                                bsflag: 1
                            }}).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            querySort({column, key, order}){
              this.formInline.key = key;
              this.formInline.order = order;
              this.query();
            }
        }
    }
</script>

<style scoped>

    .postNameClass{
        color:black;
    }

    .postNameClass >>> .ivu-input[disabled], fieldset[disabled] .ivu-input{
        color:black;
    }

</style>
